<template>
  <div class="app-container">
    <!-- 查询行 -->
    <el-row :gutter="10" class="mb8 query-row">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入查询条件" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-input v-model="queryParams.group" placeholder="请输入查询条件" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="mini"
            @change="handleQuery">
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ID" prop="id" v-show="showSearch">
          <el-input v-model="queryParams.id" placeholder="请输入查询条件" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-tooltip content="从源文件重新加载任务列表" placement="top-start" effect="dark">
          <el-button type="primary" plain size="mini" icon="el-icon-refresh-right" @click="handleReload">
            加载任务
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="重新加载所有JSON配置文件,含flow,sql,config等" placement="top-start" effect="dark">
          <el-button type="primary" plain size="mini" icon="el-icon-refresh-right" @click="handleReloadJSON">
            加载配置
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="任务临时暂停,点击加载任务后会依据配置文件重置" placement="top-start" effect="dark">
          <el-button type="primary" plain size="mini" @click="handlePauseAll" icon="el-icon-video-pause">
            暂停所有任务
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleManual" icon="el-icon-video-play" :disabled="!currentRow">
          执行
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-document" size="mini" @click="handleRunTimeInfo" :disabled="!currentRow">
          运行信息
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-document" size="mini" @click="handleFlowInfo" :disabled="!currentRow">
          流程配置
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-tooltip content="任务临时暂停,点击加载任务后会依据配置文件重置" placement="top-start" effect="dark">
          <el-button type="info" plain size="mini" @click="handlePause" icon="el-icon-video-pause" :disabled="!currentRow">
            暂停
          </el-button>
        </el-tooltip>
      </el-col>

      <el-col :span="1.5">
        <el-tooltip content="任务临时恢复,点击加载任务后会依据配置文件重置" placement="top-start" effect="dark">
          <el-button type="info" plain size="mini" @click="handleResume" icon="el-icon-refresh-left" :disabled="!currentRow">
            恢复
          </el-button>
        </el-tooltip>
      </el-col>

      <el-col :span="1.5">
        <el-button type="info" plain size="mini" @click="handleDetail" :disabled="!currentRow">
          <svg-icon icon-class="list" /> 明细
        </el-button>
      </el-col>

      <!-- <el-col :span="1.5">
        <el-input-number v-model="timeSec" :min="5" :max="600" label="秒" size="mini" :disabled="timeChecked">
        </el-input-number>
      </el-col>
      <el-col :span="1.5">
        <el-checkbox v-model="timeChecked" label="定时刷新(秒)" size="mini" border @change="handleTimeChecked"></el-checkbox>
      </el-col> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="mainTable" v-loading="loading" :data="datalist" @selection-change="handleSelectionChange"
      @cell-dblclick="handleRunTimeInfo" @current-change="handleCurrentChange" :row-style="{ height: '32px' }"
      :cell-style="{ padding: '0px' }" highlight-current-row border :height="tableHeight"
      :row-class-name="tableRowClassName">
      <!-- 取消多选框 -->
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column v-for="item in columns" :key="item" :label="item" :width="computeWidth(datalist, item)"
        align="left" :prop="item" show-overflow-tooltip />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 查看运行信息 -->
    <RunTimeDlg ref="RunTimeDlg"></RunTimeDlg>
    <!-- 查看流程配置,通过属性传入参数 -->
    <flow-info-dlg :visible.sync="flowOpen" :code="flowCode"></flow-info-dlg>
  </div>
</template>

<script>
import { list, manual, reload, pause,pauseAll, resume } from "@/api/aitcommon/aittask";
import { reload as reloadJSON } from "@/api/aitcommon/aitconfig";
import { computeColWidth,objectEqual } from "@/utils/ait";
import RunTimeDlg from '@/components/AIT/RunTimeDlg';
import FlowInfoDlg from '@/components/AIT/FlowInfo';

export default {
  name: "aittask",
  components: {RunTimeDlg,FlowInfoDlg},
  data() {
    return {
      //流程配置界面
      flowOpen: false,
      flowCode:'',

      statusOptions: [{ value: "1", label: '启用' }, { value: "-1", label: '暂停' }],
      //表格高度
      tableHeight: 500,
      // 定时刷新
      timeSec: 60,
      timeChecked: false,
      timer: {},
      // 当前行
      currentRow: null,
      // 显示字段
      columns: ["field10", "field11", "名称"],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 测试节点1表格数据
      datalist: [],
      // 弹出层标题
      title: "任务执行明细",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    console.info('created',this.$route.params);
    if(!this.$route.params.queryParams){
      this.getList();
    }
  },
  activated(){
    // console.info('activated',this.$route.params);
    // https://blog.csdn.net/cnailili/article/details/119038528
    if(this.$route.params.queryParams){
      let {queryParams}=this.$route.params;
      // console.info('queryParams',queryParams,this.queryParams);
      if(!objectEqual(queryParams,this.queryParams)){
          //如果参数发生变化,则重新加载数据
          this.queryParams=queryParams;
          this.getList();
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      // console.info('this.tableHeight',this.tableHeight)
      // window.innerHeight 浏览器窗口的可见高度，下面的 220 是除了table最大高度的剩余空间。
      let height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 220;
      this.tableHeight = height;
    })
  },
  methods: {
    // 打开流程配置信息
    handleFlowInfo() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }
      this.flowCode=this.currentRow.流程编码;
      this.flowOpen = true;
    },
    // 打开运行信息
    handleRunTimeInfo() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }
      this.flowCode=this.currentRow.流程编码;
      // console.info('currentRow',this.currentRow)
      // 通过调用子控件方法,弹出窗口,并传递参数
      this.$refs.RunTimeDlg.openDlg(this.flowCode,this.getList);
    },
    //加载task源文件
    handleReload() {
      this.$confirm('将基于task源文件初始任务清单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        reload().then(res => {
          this.getList();
          this.msgSuccess('task源文件加载完成!');
        }).finally(res=>{
          this.loading = false;
        })
      })
    },
    //加载json源文件
    handleReloadJSON() {
      this.loading = true;
      reloadJSON().then((res) => {
        //this.getList();
        this.msgSuccess('JSON文件已经重新加载!')
      }).finally(res=>{
        this.loading = false;
      });
    },
    // 表格宽度自适应
    computeWidth(datalist, col) {
      return computeColWidth(datalist, col)
    },
    handleTimeChecked(check) {
      // console.info('handleTimeChecked',check);
      if (check) {
        this.timer = window.setInterval(this.handleQuery, this.timeSec * 1000);
      } else {
        window.clearInterval(this.timer);
      }
    },
    /** 查询列表 */
    getList() {
      console.info('getList',this.queryParams);
      this.loading = true;
      let parms={...this.queryParams};
      parms.pageNum=parms.pageNum||1;
      parms.pageSize=parms.pageSize||20;
      parms.path = "";
      parms.sqlConfig = "sysflow.AITTaskQuery";

      if (parms.id)
      parms.path += ` and id like '%${parms.id}%' `;
      if (parms.name)
        parms.path += ` and 名称 like '%${parms.name}%'`;
      if (parms.group)
        parms.path += ` and 分组 like '%${parms.group}%'`;
      if (parms.status) {
        if (parms.status == 1) {
          // 启用
          parms.path += ` and 状态 != '暂停'`
        } else if (parms.status == -1) {
          // 暂停
          parms.path += ` and 状态 = '暂停'`
        }
      }
      // 查询任务
      list(parms).then((response) => {
        //重置数据
        if (response.data) {
          this.datalist = response.data.rows;
          this.total = response.data.total;
        } else {
          this.datalist = null;
          this.total = 0;
        }
        // 重置列名
        this.columns = [];
        if (this.datalist) {
          let rec = this.datalist[0];
          for (var key in rec) {
            this.columns.push(key);
          }
        }

        // 重置焦点行
        if(this.datalist&&this.currentRow){
          this.currentRow=this.datalist.find(item=>item.id===this.currentRow.id)
          if(this.currentRow){
            this.$refs.mainTable.setCurrentRow(this.currentRow)
          }
        }

        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.info('handleSelectionChange',selection)
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleCurrentChange(val) {
      // val为空时,保留原焦点行
      this.currentRow = val || this.currentRow;
      // console.info('handleCurrentChange',val,this.currentRow)
      //切换焦点行是否选中
      val && this.$refs.mainTable.toggleRowSelection(val);
    },

    /** 搜索按钮操作 */
    handleQuery() {
      // console.info('handleQuery')
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 手工触发
    handleManual() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }

      this.$confirm('是否手工同步数据?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        return manual([this.currentRow.id])
      }).then(() => {
        this.getList();
        this.msgSuccess("已触发手工同步,请查看运行信息!");
      }).catch(() => { })
    },

    // 暂停所有任务
    handlePauseAll() {
      pauseAll().then(() => {
        this.getList();
        this.msgSuccess(`任务已经临时暂停`);
      })
    },

    // 暂停任务
    handlePause() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }

      pause([this.currentRow.id]).then(() => {
        this.getList();
        this.msgSuccess(`任务[${this.currentRow.id}]已经临时暂停`);
      })
    },

    // 恢复任务
    handleResume() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }

      resume([this.currentRow.id]).then(() => {
        this.getList();
        this.msgSuccess(`任务[${this.currentRow.id}]已经临时恢复`);
      })
    },

    // 查看任务明细
    handleDetail() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }
      // 跳转指定页面,带入查询参数
      this.$router.push({
        path: "/ait/log",
        query: {
          jobId: this.currentRow.id
        }
      });
    },

    submitForm() {
      this.open = false;
    },

    cancelForm() {
      this.open = false;
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.状态 === '暂停') {
        return 'pause-row';
      } else {
        return 'normal-row';
      }
    }
  },
};
</script>



